/**
 * @Author: xzy 1453077527@qq.com
 * @Date: 2025-08-24 00:34:58
 * @LastEditors: xzy 1453077527@qq.com
 * @LastEditTime: 2025-08-26 18:37:28
 * @Description:
 */
package com.xtedu.examproject.dao.impl;

import com.xtedu.examproject.dao.base.ExaminationDao;
import com.xtedu.examproject.entity.Examination;
import com.xtedu.examproject.util.DBUtil;
import com.xtedu.examproject.util.PageHelper;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ExaminationDaoImpl implements ExaminationDao {
    @Override
    public int insert(Examination examination) throws Exception {
        String sql = "insert into examinations (start,duration,author,course_id,state,create_date,exam_name) values (?,?,?,?,?,?,?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setTimestamp(1, examination.getStartTime());
            ps.setInt(2, examination.getDuration());
            ps.setInt(3, examination.getAuthorId());
            ps.setInt(4, examination.getCourseId());
            ps.setInt(5, examination.getState());
            ps.setObject(6, examination.getCreateDate());
            ps.setString(7, examination.getExamName());
            int result = ps.executeUpdate();
            // 获取生成的主键
            if (result > 0) {
                try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        return generatedKeys.getInt(1); // 返回生成的ID
                    }
                }
            }
            return 0; // 插入失败或未生成ID
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public int update(Examination examination) throws Exception {
        String sql = "update examinations set start=?,duration=?,author=?,course_id=?,state=?,create_date=?,exam_name=? where id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setTimestamp(1, examination.getStartTime());
            ps.setInt(2, examination.getDuration());
            ps.setInt(3, examination.getAuthorId());
            ps.setInt(4, examination.getCourseId());
            ps.setInt(5, examination.getState());
            ps.setObject(6, examination.getCreateDate());
            ps.setString(7, examination.getExamName());
            ps.setInt(8, examination.getId());
            return ps.executeUpdate();
        }
    }

    @Override
    public int delete(Examination examination) throws Exception {
        String sql = "delete from examinations where id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, examination.getId());
            return ps.executeUpdate();
        }
    }

    @Override
    public int deleteById(int id) throws Exception {
        return 0;
    }

    @Override
    public Examination findById(int id) throws Exception {
        String sql = "select * from examinations where id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            Examination examination = new Examination();
            while (rs.next()) {
                examination.setId(rs.getInt(1));
                examination.setStartTime(rs.getTimestamp(2));
                examination.setDuration(rs.getInt(3));
                examination.setAuthorId(rs.getInt(4));
                examination.setCourseId(rs.getInt(5));
                examination.setState(rs.getInt(6));
                examination.setCreateDate(rs.getTimestamp(7).toLocalDateTime());
                examination.setExamName(rs.getString(8));
            }
            return examination;
        }
    }

    @Override
    public List<Examination> findAll() throws Exception {
        String sql = "SELECT e.*,c.course_name,u.user_name FROM examinations e LEFT JOIN courses c ON e.course_id = c.id left join users u on e.author = u.id WHERE e.state !=2";
        return getExaminations(sql);
    }

    private List<Examination> getExaminations(String sql) throws SQLException {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ResultSet rs = ps.executeQuery();
            List<Examination> examinations = new ArrayList<>();
            while (rs.next()) {
                Examination examination = new Examination();
                examination.setId(rs.getInt(1));
                examination.setStartTime(rs.getTimestamp(2));
                examination.setDuration(rs.getInt(3));
                examination.setAuthorId(rs.getInt(4));
                examination.setCourseId(rs.getInt(5));
                examination.setState(rs.getInt(6));
                examination.setCreateDate(rs.getTimestamp(7).toLocalDateTime());
                examination.setExamName(rs.getString(8));
                examination.setCourseName(rs.getString(10));
                examination.setAuthorName(rs.getString(11));
                examinations.add(examination);
            }
            return examinations;
        }
    }

    @Override
    public PageHelper findAllByPage(int pageindex, int pagesize) throws Exception {
        return null;
    }

    @Override
    public PageHelper findPageByRoleIds(int pageindex, int pagesize, int... roleIds) throws Exception {
        return null;
    }

    @Override
    public List<Examination> findExaminationByCourseId(int courseId) throws Exception {
        String sql = "select e.*,c.course_name,u.user_name from examinations e left join courses c on e.course_id = c.id left join users u on e.author = u.id where e.state!=2 and course_id=" + courseId;
        return getExaminations(sql);
    }

    @Override
    public int findCourseIdByExamId(int examId) {
        String sql = "select course_id from examinations where id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, examId);
            ResultSet rs = ps.executeQuery();
            int result = 0;
            if (rs.next()) {
                result = rs.getInt(1);
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}